package xin.core.jpa.naming;

import org.hibernate.HibernateException;
import org.hibernate.boot.model.naming.*;
import xin.common.utils.StringUtils;

/**
 * <pre>
 * 自定义驼峰式Implicit命名策略，兼容JPA2.0
 * </pre>
 *
 * @author lixin_ma@outlook.com
 * @version 1.0
 * @see ImplicitNamingStrategyJpaCompliantImpl
 * @since 2018/8/7 22:01
 */
public class CamelImplicitNamingStrategy extends  ImplicitNamingStrategyJpaCompliantImpl {

    public CamelImplicitNamingStrategy(){
        super();
    }

    @Override
    public Identifier determinePrimaryTableName(ImplicitEntityNameSource source) {
        if (source == null) {
            throw new HibernateException("Entity naming information was not provided.");
        } else {
            String tableName = this.transformEntityName(source.getEntityNaming());
            if (tableName == null) {
                throw new HibernateException("Could not determine primary table name for entity");
            } else {
                return this.toIdentifier(StringUtils.toUnderScoreCase(tableName), source.getBuildingContext());
            }
        }
    }

    /**
     * TODO 此处带待实现一个更好的外键命名方式
     */
    @Override
    public Identifier determineForeignKeyName(ImplicitForeignKeyNameSource source) {
        return this.toIdentifier(NamingHelper.INSTANCE.generateHashedFkName("FK", source.getTableName(), source.getReferencedTableName(), source.getColumnNames()), source.getBuildingContext());
    }
}
